<template>
	<div> 
		<div class="main" v-if="list.length>0">
			<div class="goods" v-for="(item,index) in list" :key="index">
				<span class="check"><input type="checkbox" @click="selectGoods(index)" :checked="item.isSelect"> </span>
				<span class="name">
					<img :src="item.img">
					{{item.name}}
				</span> 
				<span class="unitPrice">{{item.unitPrice}}元</span> 
				<span class="num"> 
					<span @click="reduce(index)" :class="{off:item.num==1}">-</span>
						{{item.num}} 
					<span @click="add(index)">+</span> 
				</span> 
				<span class="unitTotalPrice">{{item.unitPrice * item.num}}元</span> 
				<span class="operation"> 
					<a @click="remove(index)">删除</a> 
				</span> 
			</div> 
		</div>
		<div v-else>购物车为空</div>
		<div class="info"> 
			<span><input type="checkbox" @click="selectAll" :checked="isSelectAll">全选</span> 
			<span>已选商品<span class="totalNum">{{totalNum}}</span> 件</span> 
			<span>合计:<span class="totalPrice">¥{{totalPrice}}</span>元</span> 
			<span>去结算</span> 
		</div> 
	</div>
</template>

<script>
export default{
	data: function () {
		return {
			isSelectAll : false, //默认未全选
			list : [{ 
				img : require("@/assets/images/honor.jpg"),
				name : "华为 P20 4G手机 双卡双待", 
				num : 1, 
				unitPrice : 2399, 
				isSelect : false 
			},{ 
				img : require("@/assets/images/oppo.jpg"),
				name : "OPPO R15 智能手机 全网通", 
				num : 2, 
				unitPrice : 2699, 
				isSelect : false
			},{ 
				img : require("@/assets/images/vivo.jpg"),
				name : "vivo X27 8GB+256GB大内存", 
				num : 1, 
				unitPrice : 3588, 
				isSelect : false 
			}]  
		}
	},
	computed : { 
		totalNum : function(){ //计算商品件数
			var totalNum = 0; 
			this.list.forEach(function(item){
				if(item.isSelect){ 
					totalNum+=1;
				}
			});
			return totalNum;
		},
		totalPrice : function(){ //计算商品总价
			var totalPrice = 0; 
			this.list.forEach(function(item){
				if(item.isSelect){ 
					totalPrice += item.num*item.unitPrice;
				}
			});
			return totalPrice;
		} 
	},
	methods : { 
		reduce : function(index){ //减少商品个数
			var goods = this.list[index];
			if(goods.num >= 2){
				goods.num--;
			}
		}, 
		add : function(index){ //增加商品个数
			var goods = this.list[index];
			goods.num++;
		},
		remove : function(index){ //移除商品
			this.list.splice(index,1);
		}, 
		selectGoods : function(index){ //选择商品
			var goods = this.list[index];
			goods.isSelect = !goods.isSelect; 
			this.isSelectAll = true;
			for(var i = 0;i < this.list.length; i++){
				if(this.list[i].isSelect == false){ 
					this.isSelectAll=false;
				}
			}
		},
		selectAll : function(){ //全选或全不选
			this.isSelectAll = !this.isSelectAll; 
			for(var i = 0;i < this.list.length; i++){
				this.list[i].isSelect = this.isSelectAll;
			}
		} 
	}  
}
</script>
